import os
import zipfile
import sys

def extract_zip(zip_path, extract_dir):
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        zip_ref.extractall(extract_dir)


def compare_directories(dir1, dir2):
    inconsistencies = []

    for root, dirs, files in os.walk(dir1):
        relative_path = os.path.relpath(root, dir1)
        corresponding_dir = os.path.join(dir2, relative_path)

        if not os.path.exists(corresponding_dir) or not os.path.isdir(corresponding_dir):
            inconsistencies.append(f"Directory mismatch: {os.path.join(root)}")
            continue

        dir1_dirs = set(dirs)
        dir2_dirs = set(next(os.walk(corresponding_dir))[1])

        if dir1_dirs != dir2_dirs:
            inconsistencies.append(f"Directory name mismatch: {os.path.join(root)}")

        dir1_files = set(files)
        dir2_files = set(next(os.walk(corresponding_dir))[2])

        if dir1_files != dir2_files:
            inconsistencies.append(f"File name mismatch: {os.path.join(root)}")

        # Check number of directories and files
        if len(dirs) > len(dir2_dirs):
            inconsistencies.append(f"Extra directories in first input: {os.path.join(root)}")
        elif len(dirs) < len(dir2_dirs):
            inconsistencies.append(f"Extra directories in second input: {os.path.join(root)}")

        if len(files) > len(dir2_files):
            inconsistencies.append(f"Extra files in first input: {os.path.join(root)}")
        elif len(files) < len(dir2_files):
            inconsistencies.append(f"Extra files in second input: {os.path.join(root)}")

    return inconsistencies


if __name__ == '__main__':
    if len(sys.argv) != 3:
        print("Usage: python3 zip_compare.py <input1> <input2>")
        sys.exit(1)

    input1 = sys.argv[1]
    input2 = sys.argv[2]

    extracted_dirs = []

    try:
        if input1.endswith('.zip'):
            extract_dir = os.path.splitext(os.path.basename(input1))[0]
            os.makedirs(extract_dir, exist_ok=True)
            extract_zip(input1, extract_dir)
            input1 = extract_dir
            extracted_dirs.append(extract_dir)

        if input2.endswith('.zip'):
            extract_dir = os.path.splitext(os.path.basename(input2))[0]
            os.makedirs(extract_dir, exist_ok=True)
            extract_zip(input2, extract_dir)
            input2 = extract_dir
            extracted_dirs.append(extract_dir)

        inconsistencies = compare_directories(input1, input2)

        if inconsistencies:
            with open('result.txt', 'w') as result_file:
                for inconsistency in inconsistencies:
                    result_file.write(inconsistency + '\n')
            print("Inconsistencies found. Details written to result.txt")
        else:
            print("The contents of the inputs are identical.")

    finally:
        # Extracted directories are preserved, no cleanup needed
        pass
